from django.shortcuts import render
from rest_framework.generics import ListAPIView,GenericAPIView,CreateAPIView
from rest_framework.response import Response
from .serializers import SkuSerializer, UserBrowsingHistorySerializer
from .models import GoodsCategory,SKU
from rest_framework.filters import OrderingFilter
# Create your views here.
from .utils import StandardResultsSetPagination
from drf_haystack.viewsets import HaystackViewSet
from .serializers import SKUIndexSerializer,SkuSerializer
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection

# 如果全局布局分页器ListAPIView都会分页，里面写了分页方法
class SkuListView(ListAPIView):
    serializer_class = SkuSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time','price','sales']

    def get_queryset(self):
        pk = self.kwargs['pk']
        sku = SKU.objects.filter(category_id=pk)
        return sku


class SKUSerachView(HaystackViewSet):

    index_models = [SKU]
    # pagination_class = StandardResultsSetPagination
    serializer_class = SKUIndexSerializer


class UserBrowsingHistoryView(CreateAPIView):
    serializer_class = UserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]
    # def get_queryset(self):
    #     return SKU.objects.filter(id=self.request.data['sku_id'])

    # def post(self,request):
    #
    #     # 获取sku_id
    #     ser = self.serializer_class(data=request.data,context={'request':request})
    #     ser.is_valid(raise_exception=True)
    #     ser.save()

    def get(self,request):
        user_id = request.user.id
        conn = get_redis_connection('history')
        # pl = conn.pipeline()
        # 获取到的是一个列表
        history = conn.lrange('history_%s'%user_id,0,4)
        skus = []
        # 添加每个sku对象到列表中
        for sku_id in history:
            # get查询出来的是一个对象，filter查询出来的是查询集，所以不能用filter
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)
        # 返回查询集，需要用到对象的所有字段
        ser = SkuSerializer(skus,many=True)

        return Response(ser.data)